<script lang="ts" setup>
import type { RowType } from './types';
import { $t } from '#/locales';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';

import {
  Button,
  Dropdown,
  Menu,
  MenuItem,
  message,
  Modal,
  Popconfirm,
  Space,
  Switch,
} from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteNavs, getNavs, putNavs } from '#/api/admin/navs';
import Icon from '#/components/Icons';

import { FormModalView, TableModalView } from './components';

defineOptions({
  name: 'AdminNav',
});

const router = useRouter();
const routeMeta = router.currentRoute.value.meta;
const viewTitle = routeMeta.title.replace('管理', '');

const gridOptions: VxeGridProps<RowType> = {
  rowConfig: {
    isCurrent: true,
    isHover: true,
  },
  pagerConfig: {
    enabled: false,
  },
  columns: [
    { title: $t("page.common.Code"), type: 'seq', width: 50 },
    { field: 'name', title: $t("page.common.Name") },
    // { field: 'is_main', title: '主菜单', slots: { default: 'is_main' } },
    { field: 'remark', title: $t("admin.Remark") },
    {
      slots: { default: 'action' },
      field: 'action',
      fixed: 'right',
      title: $t("page.common.Action"),
      width: 240,
    },
  ],
  height: 'auto',
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async () => {
        const { data } = await getNavs();
        return data;
      },
    },
  },
  toolbarConfig: {
    custom: true,
    // export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, GridApi] = useVbenVxeGrid({
  gridOptions,
});

const handleDelete = async (row: RowType) => {
  const $table = GridApi.grid;
  if ($table) {
    const { msg } = await deleteNavs(row);
    $table.remove(row);
    message.success(msg);
  }
};

const onChange = async (scope: { row: RowType; rowIndex: number }) => {
  Modal.confirm({
    title: '系统提示',
    content: `确认要${scope.row.is_main === 0 ? '停用' : '启用'}${
      scope.row.name
    }吗?`,
    async onOk() {
      try {
        await putNavs({
          id: scope.row.id,
          name: scope.row.name,
          is_main: scope.row.is_main,
          remark: scope.row.remark,
        });
        message.success(
          `已${scope.row.is_main === 0 ? '停用' : '启用'}${scope.row.name}`,
        );
        GridApi.query();
      } catch {
        scope.row.is_main === 0
          ? (scope.row.is_main = 1)
          : (scope.row.is_main = 0);
      }
    },
    onCancel() {
      scope.row.is_main === 0
        ? (scope.row.is_main = 1)
        : (scope.row.is_main = 0);
    },
  });
};

const [TableModal, tableModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: TableModalView,
});

const openMoreDialog = (row?: RowType, title: string = '') => {
  tableModalApi.setState({
    title: `${row?.name}--${viewTitle}${title}`,
  });
  tableModalApi.setData(row);
  tableModalApi.open();
};

const [FormModal, formModalApi] = useVbenModal({
  // 连接抽离的组件
  connectedComponent: FormModalView,
  onClosed() {
    const formModalData = formModalApi.getData();
    if (formModalData?.isUpdata) {
      GridApi.query();
    }
  },
});

const openDialog = async (title: 'Edit' | 'Add', row?: null | RowType) => {
  formModalApi.setState({
    title: $t("page.common."+title)+" "+`${viewTitle}`,
  });
  formModalApi.setData(row);
  formModalApi.open();
};
</script>

<template>
  <Page auto-content-height>
    <TableModal />
    <FormModal />
    <Grid :table-title="$t('page.common.List')">
      <template #toolbar-tools>
        <Button class="mr-2" type="primary" @click="openDialog('Add')">
          <span class="anticon">
            <Icon icon="ri:add-line" />
          </span>
          {{$t("page.common.Add")}}
        </Button>
      </template>
      <template #is_main="{ row, rowIndex }">
        <Switch
          v-model:checked="row.is_main"
          :checked-value="1"
          :disabled="row.is_main === 1 ? true : false"
          :un-checked-value="1"
          checked-children="启用"
          un-checked-children="停用"
          @change="onChange({ row, rowIndex })"
        />
      </template>

      <template #action="{ row }">
        <Space>
          <Button type="primary" @click="openDialog('Edit', row)">
            <template #icon>
              <span class="anticon">
                <Icon icon="ri:file-edit-line" />
              </span>
            </template>
            {{$t("page.common.Edit")}}
          </Button>
          <Popconfirm
            :disabled="row.is_main === 1 ? true : false"
            cancel-text="否"
            ok-text="是"
            title="确认删除？"
            @confirm="handleDelete(row)"
          >
            <Button
              :disabled="row.is_main === 1 ? true : false"
              danger
              type="primary"
            >
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:delete-bin-line" />
                </span>
              </template>
              {{$t("page.common.Delete")}}
            </Button>
          </Popconfirm>
          <Dropdown>
            <Button type="link">
              <template #icon>
                <span class="anticon">
                  <Icon icon="ri:more-fill" />
                </span>
              </template>
            </Button>
            <template #overlay>
              <Menu>
                <MenuItem>
                  <Button type="link" @click="openMoreDialog(row)">
                    <template #icon>
                      <span class="anticon">
                        <Icon icon="ri:file-list-3-line" />
                      </span>
                    </template>
                    {{$t("page.menu.Data")}}
                  </Button>
                </MenuItem>
              </Menu>
            </template>
          </Dropdown>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
